package cn.touna.jss.common.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.Map.Entry;

public class HttpClientUtils {
    private final static Logger LOGGER = LoggerFactory.getLogger(HttpClientUtils.class);

    private RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(120000)
            .setConnectTimeout(120000)
            .setConnectionRequestTimeout(120000)
            .build();

    /**
     * post请求
     *
     * @param url  请求地址
     * @param json 参数json串
     * @return json结果
     */
    public static String httpPost(String url, String json) {
        //post请求返回结果
        DefaultHttpClient httpClient = new DefaultHttpClient();
        JSONObject jsonResult = null;
        HttpPost method = new HttpPost(url);
        HttpResponse result = null;
        try {
            if (null != json && !"".equals(json)) {
                //解决中文乱码问题
                StringEntity entity = new StringEntity(json, "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                method.setEntity(entity);
            }
            result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");
            /**请求发送成功，并得到响应**/
            if (result.getStatusLine().getStatusCode() == 200) {
                String str = "";
                try {
                    /**读取服务器返回过来的json字符串数据**/
                    str = EntityUtils.toString(result.getEntity());
                    /**把json字符串转换成json对象**/
                    jsonResult = JSONObject.parseObject(str);
                } catch (Exception e) {
                    LOGGER.error("POST Request Failed: " + url, e);
                }
            } else {
                method.abort();
            }
        } catch (IOException e) {
            LOGGER.error("POST Request Failed: " + url, e);
        }
        return jsonResult == null ? "" : jsonResult.toString();
    }

    public static JSONObject httpPost(String url, JSONObject jsonParam, boolean noNeedResponse) {
        //post请求返回结果
        DefaultHttpClient httpClient = new DefaultHttpClient();
        JSONObject jsonResult = null;
        HttpPost method = new HttpPost(url);
        try {
            if (null != jsonParam) {
                //解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                method.setEntity(entity);
            }
            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");
            /**请求发送成功，并得到响应**/
            if (result.getStatusLine().getStatusCode() == 200) {
                String str = "";
                try {
                    /**读取服务器返回过来的json字符串数据**/
                    str = EntityUtils.toString(result.getEntity());
                    if (noNeedResponse) {
                        return null;
                    }
                    /**把json字符串转换成json对象**/
                    jsonResult = JSONObject.parseObject(str);
                } catch (Exception e) {
                    LOGGER.error("POST Request Failed: " + url, e);
                }
            } else {
                method.abort();
            }
        } catch (IOException e) {
            LOGGER.error("POST Request Failed: " + url, e);
        }
        return jsonResult;
    }

    public static JSONObject httpGet(String url) {
        LOGGER.info("request url: " + url);
        //get请求返回结果
        JSONObject jsonResult = null;
        try {
            HttpClient client = new DefaultHttpClient();
            //发送get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);

            LOGGER.info("response code: " + response.getStatusLine().getStatusCode());

            /**请求发送成功，并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数据**/
                String strResult = EntityUtils.toString(response.getEntity());
                /**把json字符串转换成json对象**/
                jsonResult = JSONObject.parseObject(strResult);
//                url = URLDecoder.decode(url, "UTF-8");
            } else {
                //jsonResult =
                request.abort();
                LOGGER.error("GET Request Failed: " + url);
            }
        } catch (IOException e) {
            LOGGER.error("GET Request Failed: " + url, e);
        }
        return jsonResult;
    }

    public String doPost(String url, Map<String, String> map, String charset) {
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            //设置参数
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            Iterator iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, String> elem = (Entry<String, String>) iterator.next();
                list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
            }
            if (list.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
                httpPost.setEntity(entity);
            }
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, charset);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        String url = "https://apitest.tongdun.cn/preloan/apply/v5";
        String charset = "utf-8";
        HttpClientUtils httpClientUtil = new HttpClientUtils();
        Map<String, String> createMap = new HashMap<String, String>();
        createMap.put("partner_code", "touna");
        createMap.put("partner_key", "21714e426ff943da97acaa9e6b16a041");
        createMap.put("app_name", "tounaCD_web");
        createMap.put("id_number", "340103198007018430");
        createMap.put("mobile", "15625273902");
        createMap.put("name", "冯成成");
        String httpOrgCreateTestRtn = httpClientUtil.doPost(url, createMap, charset);
        System.out.println("result:" + httpOrgCreateTestRtn);
    }


}
